package com.tnstudio.tuneup_one_click;



import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import com.google.android.gms.ads.*;
import com.ironsource.mobilcore.*;
import com.ironsource.mobilcore.MobileCore.AD_UNITS;
import com.ironsource.mobilcore.MobileCore.LOG_TYPE;


import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.pm.IPackageDataObserver;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;


public class MainActivity extends Activity {
	public ImageButton btnStart;
	public TextView tvAvaibleMem;
	public TextView tvUsedMem;
	public TextView tvAvaibleStora;
	public TextView tvUsedStora;
	public CheckBox cbCleanApp;
	public CheckBox cbCleanBack;
	public CheckBox cbCleanJunk;

	long totRam = 0;
	long freeRam = 0;
	long usedRam = 0;
	long Cached = 0;

	int app_count = 0;
	ProgressDialog progressBar;
	private int progressBarStatus = 0;
	private Handler progressBarHandler = new Handler();
	private long fileSize = 0;	

	private InterstitialAd interstitial;
	private Activity mActivity;
	
	private static final long CACHE_APP = Long.MAX_VALUE;
	private CachePackageDataObserver mClearCacheObserver;

	public void Init() {
		btnStart = (ImageButton) findViewById(R.id.btnStart);

		tvAvaibleMem = (TextView) findViewById(R.id.tvAvaibleMem);
		tvUsedMem = (TextView) findViewById(R.id.tvUsedMem);
		tvAvaibleStora = (TextView) findViewById(R.id.tvAvaibleStora);
		tvUsedStora = (TextView) findViewById(R.id.tvUsedStora);

		cbCleanApp = (CheckBox) findViewById(R.id.cbCleanApp);
		cbCleanBack = (CheckBox) findViewById(R.id.cbCleanRunningBackApp);
		cbCleanJunk = (CheckBox) findViewById(R.id.cbCleanJunk);
		Binding();
		getMemoryInfo();
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
//		 Create the interstitial.
		interstitial = new InterstitialAd(this);
		interstitial.setAdUnitId(AdvID.admobId);

		// Create ad request.
		AdRequest adRequest = new AdRequest.Builder().build();

		// Begin loading your interstitial.
		interstitial.loadAd(adRequest);

		interstitial.setAdListener(new AdListener() {
			public void onAdLoaded() {
				displayInterstitial();
			};

			@Override
			public void onAdFailedToLoad(int errorCode) {
				MobileCore.showOfferWall(MainActivity.this, null);
				super.onAdFailedToLoad(errorCode);
			}
		});

		mActivity = this;
		MobileCore.init(this, AdvID.mobileCoreId, LOG_TYPE.DEBUG,
				AD_UNITS.ALL_UNITS);
		showStickeezWhenReady();
		
		Init();
		
	}

	private void showStickeezWhenReady() {
		MobileCore.setStickeezReadyListener(new OnReadyListener() {
			@Override
			public void onReady(AD_UNITS adUnit) {
				if (adUnit == AD_UNITS.STICKEEZ) {
					MobileCore.showStickee(mActivity);
				}
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	public void displayInterstitial() {
		if (interstitial.isLoaded()) {
			interstitial.show();
		}
	}

	public void Binding() {
		btnStart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// prepare for a progress bar dialog
				
				BtnStartOnclick(v);
				
			}
		});

	}

	protected void BtnStartOnclick(View v) {
		if (MobileCore.isStickeeReady()) {
			MobileCore.showStickee(mActivity);
		}
		
		if (cbCleanApp.isChecked())
			clearCache();

		if (cbCleanBack.isChecked())
			ClearRunning();
		//Show Processing
		progressBar = new ProgressDialog(v.getContext());
		progressBar.setCancelable(true);
		progressBar.setMessage("Cleaning ...");
		progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressBar.setProgress(0);
		progressBar.setMax(100);
		progressBar.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss(DialogInterface dialog) {
			ShowAlert();
			getMemoryInfo();	
			}
		});
		progressBar.show();

		//reset progress bar status
		progressBarStatus = 0;

		//reset filesize
		fileSize = 0;
		
		new Thread(new Runnable() {
		  public void run() {
			  
			while (progressBarStatus < 100) {

			  // process some tasks
			  progressBarStatus = 100;

			  // your computer is too fast, sleep 1 second
			  try {
				Thread.sleep(1000);
			  } catch (InterruptedException e) {
				e.printStackTrace();
			  }

			  // Update the progress bar
			  progressBarHandler.post(new Runnable() {
				public void run() {
				  progressBar.setProgress(progressBarStatus);
				}
			  });
			}

			// ok, file is downloaded,
			if (progressBarStatus >= 100) {

				// sleep 2 seconds, so that you can see the 100%
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				// close the progress bar dialog
				progressBar.dismiss();
			}
		  }
	       }).start();
		//ShowAlert
		
	}
	private void ClearAllCache() {
		Class<?> myClass = null;
		try {
			myClass = Class.forName("android.content.pm.PackageManager");
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			Method method = myClass.getMethod("deleteApplicationCacheFiles",
					String.class, IPackageDataObserver.class);
		} catch (NoSuchMethodException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		PackageManager pm = getPackageManager();
		// Get all methods on the PackageManager
		Method[] methods = pm.getClass().getDeclaredMethods();
		for (Method m : methods) {
			if (m.getName().equals("freeStorageAndNotify")) {
				// Found the method I want to use
				try {
					double desiredFreeStorage = Long.MAX_VALUE;
					; // Request for 8GB of free space
					m.invoke(pm, desiredFreeStorage, null);
				} catch (Exception e) {
					// Method invocation failed. Could be a permission problem
				}
				break;
			}
		}
	}

	// Clear cache
	private void ClearRunning() {
		app_count  = 0;
		ActivityManager manager = (ActivityManager) this
				.getSystemService(ACTIVITY_SERVICE);
		List<RunningAppProcessInfo> activityes = ((ActivityManager) manager)
				.getRunningAppProcesses();

		for (int i = 0; i < activityes.size(); i++) {

			Log.e("APP: " + i, activityes.get(i).processName);

			if (!activityes.get(i).processName
					.equals(AdvID.pack)) {
				app_count++;
				android.os.Process.killProcess(activityes.get(i).pid);
			}

		}

	}

	public void clearApplicationData() {
		File cache = getCacheDir();
		File appDir = new File(cache.getParent());
		if (appDir.exists()) {
			String[] children = appDir.list();
			for (String s : children) {
				if (!s.equals("lib")) {
					deleteDir(new File(appDir, s));
					Log.i("TAG",
							"**************** File /data/data/APP_PACKAGE/" + s
									+ " DELETED *******************");
				}
			}
		}
	}

	public static boolean deleteDir(File dir) {
		if (dir != null && dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}

		return dir.delete();
	}

	void clearCache() {
		if (mClearCacheObserver == null) {
			mClearCacheObserver = new CachePackageDataObserver();
		}

		PackageManager mPM = getPackageManager();

		@SuppressWarnings("rawtypes")
		final Class[] classes = { Long.TYPE, IPackageDataObserver.class };

		Long localLong = Long.valueOf(CACHE_APP);

		try {
			Method localMethod = mPM.getClass().getMethod(
					"freeStorageAndNotify", classes);

			/*
			 * Start of inner try-catch block
			 */
			try {
				localMethod.invoke(mPM, localLong, mClearCacheObserver);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			/*
			 * End of inner try-catch block
			 */
		} catch (NoSuchMethodException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}// End of clearCache() method

	private class CachePackageDataObserver extends IPackageDataObserver.Stub {
		public void onRemoveCompleted(String packageName, boolean succeeded) {

		}// End of onRemoveCompleted() method
	}// End of CachePackageDataObserver instance inner class

	private void getMemoryInfo() {
		getTotalRAM();
		tvAvaibleMem.setText(""+MemoryStatus.formatSize(freeRam,2));
		tvUsedMem.setText(""+MemoryStatus.formatSize(usedRam,2));
		tvAvaibleStora.setText(""
				+MemoryStatus.formatSize(
						MemoryStatus.getAvailableInternalMemorySize(),1
//						+
//						MemoryStatus.getAvailableExternalMemorySize()
						)
				);
		tvUsedStora.setText(""+MemoryStatus.formatSize(
				MemoryStatus.getTotalInternalMemorySize()
				-
				MemoryStatus.getAvailableInternalMemorySize(),1
				));
		Cached = getTotalCache_Buffer();
	}

	public void getTotalRAM() {

		RandomAccessFile reader = null;
		String load = null;
		DecimalFormat twoDecimalForm = new DecimalFormat("#.##");

		String lastValue = "";
		try {
			reader = new RandomAccessFile("/proc/meminfo", "r");
			load = reader.readLine();

			// Get the Number value from the string
			Pattern p = Pattern.compile("(\\d+)");
			Matcher m = p.matcher(load);
			String value = "";
			while (m.find()) {
				value = m.group(1);
				// System.out.println("Ram : " + value);
			}
			//Free
			load = reader.readLine();
			// Get the Number2 value from the string
			m = p.matcher(load);

			while (m.find()) {

				freeRam = Long.parseLong(m.group(1));
			}
			
			reader.close();
			
			totRam = Long.parseLong(value);
			usedRam = totRam - freeRam;
			// totRam = totRam / 1024;

			double mbTotal = totRam / 1024.0;
			double mbUsed = usedRam / 1024.0;
			double mbFree = freeRam / 1024.0;

			

		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			// Streams.close(reader);
		}

		// return lastValue;
	}
	public long getTotalCache_Buffer() {
		
		long Cached1 = Long.MIN_VALUE;
		RandomAccessFile reader = null;
		String load = null;
		DecimalFormat twoDecimalForm = new DecimalFormat("#.##");

		String lastValue = "";
		try {
			reader = new RandomAccessFile("/proc/meminfo", "r");
			load = reader.readLine();
			load = reader.readLine();
			load = reader.readLine();
			// Get the Number value from the string
			Pattern p = Pattern.compile("(\\d+)");
			Matcher m = p.matcher(load);
			String value = "";
			
			//Cache
			load = reader.readLine();
			// Get the Number2 value from the string
			m = p.matcher(load);

			while (m.find()) {

				Cached1 = Long.parseLong(m.group(1));
			}
			reader.close();
			
		
			return Cached1;
			

		} catch (IOException ex) {
			
			ex.printStackTrace();
			return Cached;
		} finally {
			// Streams.close(reader);
		}

		// return lastValue;
	}
	@Override
	public void onBackPressed() {
		MobileCore.showOfferWall(this, new CallbackResponse() {
			@Override
			public void onConfirmation(TYPE type) {
				finish();
			}
		});
	}
	Dialog custom;
	private void ShowAlert() {
		 getTotalRAM();
		
		custom = new Dialog(MainActivity.this);
        custom.setContentView(R.layout.custom_alert);
        custom.setTitle("CLEAN RESULT");
        ImageButton btn = (ImageButton)custom.findViewById(R.id.ibtnClose);
        btn.setOnClickListener(new OnClickListener() {
        	
				@Override
				public void onClick(View v) {
					custom.dismiss();
				}
				});
        TextView tvcache_removed1 = (TextView)custom.findViewById(R.id.tvcache_removed);  
        TextView tvjunk_removed1 = (TextView)custom.findViewById(R.id.tvjunk_removed);   
        TextView tvapp_stop1 = (TextView)custom.findViewById(R.id.tvapp_stop);  
        TextView tvAvailMemo_d = (TextView)custom.findViewById(R.id.tvAvailMemo_d);
        TextView tvAvaiStore_d = (TextView)custom.findViewById(R.id.tvAvaiStore_d);
        
        tvcache_removed1.setText(""+MemoryStatus.formatSize((getTotalCache_Buffer()-Cached),2));
        tvjunk_removed1.setText("OK");
        tvapp_stop1.setText(app_count);
        
        tvAvailMemo_d.setText(""+MemoryStatus.formatSize(freeRam,2));
        tvAvaiStore_d.setText(MemoryStatus.formatSize(
				MemoryStatus.getAvailableInternalMemorySize(),1));
        
     
		
        
	    custom.show();
	        
		
	}
	
	
	
	
}
